using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using Services.Activity.Domain.Entities;
using Services.Identity.SDK;
using Services.Initial.PublicProject.PublicClass.ExtensionException;
using System.Drawing;
using Zack.JWT;
namespace Services.Activity.Domain;
public class IDomainService(IActivityRepository activityRepository, IWebHostEnvironment webHostEnvironment, IHttpContextAccessor httpContextAccessor, IOptionsSnapshot<JWTOptions> jWTOptions, ITokenService tokenService, IHttpClientFactory httpClientFactory)
{
    private readonly IActivityRepository activityRepository = activityRepository;
    private readonly IWebHostEnvironment webHostEnvironment = webHostEnvironment;
    private readonly IHttpContextAccessor httpContextAccessor = httpContextAccessor;
    private readonly JWTOptions jWTOptions = jWTOptions.Value;
    private readonly ITokenService tokenService = tokenService;
    private readonly IHttpClientFactory httpClientFactory = httpClientFactory;
    public async Task<long> ActivityAddAsync(VoluntaryActivity voluntaryActivity)
    {
        var res = await activityRepository.AddAsync(voluntaryActivity);
        return res.ActivityId;
    }

    public async Task EnlistVolunteerAsync(long activityId, long volunteerId)
    {
        var result = await this.activityRepository.ActivityAddVolunteerAsync(activityId, volunteerId);
        if (!result)
        {
            throw new ExceptionWithStatus(httpStatusCode: System.Net.HttpStatusCode.InternalServerError, "志愿活动参加失败，请稍后再试。");
        }
    }

    public async Task<List<VoluntaryActivity>> GetActivitiesDetailAsync(List<long> id)
    {
        return await this.activityRepository.GetActivitiesDetailAsync(id);
    }

    public async Task<List<VoluntaryActivity>> GetOrganizerActivityAsync(long userId)
    {
        return await this.activityRepository.GetOrganizerActivityAsync(userId);
    }

    public async Task<List<VoluntaryActivity>> GetVolunteerActivityListAsync(long userId)
    {
        return await this.activityRepository.GetVolunteerActivityListAsync(userId);
    }

    public async Task<string> SaveBase64PhotoToImageAsync(string activityAdvertisePhotoBase64, string activityName)
    {
        return await Task.Run(() =>
         {
             int index = activityAdvertisePhotoBase64.IndexOf(",");
             if (index != -1)
             {
                 activityAdvertisePhotoBase64 = activityAdvertisePhotoBase64.Substring(index + 1);
             }
             // 将base64字符串转换为字节数组
             byte[] imageBytes = Convert.FromBase64String(activityAdvertisePhotoBase64);
             using var stream = new MemoryStream(imageBytes);
             var image = Image.FromStream(stream);
             var bitmap = new Bitmap(image);
             DateTime today = DateTime.Today;
             //用日期把文件分散在不同文件夹存储，同时由于加上了文件hash值作为目录，又用用户上传的文件夹做文件名，
             //所以几乎不会发生不同文件冲突的可能
             //用用户上传的文件名保存文件名，这样用户查看、下载文件的时候，文件名更灵活
             string key = $"{today.Year}/{today.Month}/{today.Day}/{activityName}.{image.RawFormat.ToString().ToLower()}";
             string fullPath = Path.Combine(webHostEnvironment.ContentRootPath, "wwwroot", key);
             string? fullDir = Path.GetDirectoryName(fullPath);//get the directory
             if (!Directory.Exists(fullDir))//automatically create dir
             {
                 Directory.CreateDirectory(fullDir);
             }
             if (File.Exists(fullPath))//如果已经存在，则尝试删除
             {
                 File.Delete(fullPath);
             }
             bitmap.Save(fullPath);
             var req = httpContextAccessor.HttpContext.Request;
             return req.Scheme + "://" + req.Host + ":900" + "/VoluntaryActivity/" + key;
         });
    }

    /// <summary>
    ///  筛选活动按照条件
    /// </summary>
    /// <returns></returns>
    public async Task<List<long>> FilterActityIdsByRequestAsync(string? activityName, string? organizerName, int? activityType, DateTime? activityStartTime, DateTime? activityEndTime, string? activityBriefAddress)
    {
        List<Func<VoluntaryActivity, bool>> funcList = new();
        //定义多个查询func委托
        if (!string.IsNullOrEmpty(activityName))
        {
            funcList.Add((a) =>
            {
                return a.ActivityName.Intersect(activityName).Any();
            });
        }
        if (!string.IsNullOrEmpty(organizerName))
        {
            var identityClient = new IdentityClient(this.tokenService, this.jWTOptions, this.httpClientFactory);
            var userIds = (await identityClient.GetUserInformationByNamesAsync([organizerName])).Select(u => long.Parse(u.Item1)).ToList();
            if (userIds.Count > 0)
            {
                funcList.Add((a) =>
                {
                    return userIds.Contains(a.OrganizerId);
                });
            }
        }
        if (activityType.HasValue)
        {
            funcList.Add((a) =>
            {
                return (int)a.ActivityType == activityType.Value;
            });
        }
        if (activityStartTime.HasValue)
        {
            funcList.Add((a) =>
            {
                return a.ActivityStartTime >= activityStartTime.Value;
            });
        }
        if (activityEndTime.HasValue)
        {
            funcList.Add((a) =>
            {
                return a.ActivityCompleteTime <= activityEndTime.Value;
            });
        }
        if (!string.IsNullOrEmpty(activityBriefAddress))
        {
            funcList.Add((a) =>
            {
                return a.ActivityDetailAddress.Intersect(activityBriefAddress).Any();
            });
        }
        //查询数据库
        var result = await activityRepository.FilterActivityAsync(funcList);
        //遍历查询条件，并将符合条件的活动id加入list
        return result;

    }

    public async Task<bool> VolunteerSignAsync(long activityId, long volunteerId)
    {
        var activityVolunteer = await this.activityRepository.GetActivityVolunteerAsync(activityId, volunteerId);
        if (activityVolunteer.IsSignedIn)
        {
            throw new ExceptionWithStatus(httpStatusCode: System.Net.HttpStatusCode.Conflict, "志愿者已签到。");
        }
        return await this.activityRepository.SignInVolunteerAsync(activityVolunteer);
    }


    /// <summary>
    /// 获取活动的报名人员列表
    /// </summary>
    /// <param name="allList"></param>
    /// <param name="briefList"></param>
    /// <returns></returns>
    private List<long> ComputedListIntersec(ref List<long> allList, List<long> briefList)
    {
        if (allList.Count == 0)
        {
            allList.AddRange(briefList);
            return allList;
        }
        else
        {
            return allList.Intersect(briefList).ToList();
        }
    }
}